/**
 * Created by PhpStorm.
 * User:  iyahe@qq.com (天明)
 * Date: 2019/11/23
 * Time: 13:34
 * Description:
 */
const XLSX = require('xlsx');
export default {
  /**
   * 根据文件读取指定的shoot
   * @param file
   * @param shoot
   * @param config
   */
  readJson:function (file, shoot = 'Sheet1', config = {}) {
    //读取的表格内容的字段,
    return new Promise((resolve, reject) => {
      var that = this;
      try{
        config.readTableKey = config.readTableKey || 'v';
        if (file.name.indexOf('xlsx') >= 0) {
          that.table = [];
          var user = [];
          var tableCount = 0;
          this.readFile(file, function (list) {
            if (shoot) {
              // 拿到文件, 读取固定的user
             try {
               user = list.Sheets[shoot];
               // 获取文件的行数
               tableCount = user['!ref'].split(':')[1].substr(1, 10);
             } catch (e) {
               reject('读取失败,表格数据不完整或者表格Sheet名称传入有误,请检查!!!');
             }
            } else {
              reject('读取失败, 请传入表格Sheet名称');
            }
            // 获取到有值的数据
            let tableArr = user;
            // 表头的key. 默认读取横向从A-Z
            let azHead = config.aZ || that.aZ();
            let numerArr = [];
            // 准备合成表头的key
            for (var i = 1; i <= tableCount; i++) {
              numerArr.push(i);
            }
            let readArr = [];
            numerArr.forEach((value) => {
              let thatRead = [];
              azHead.map((val) => {
                const tempKeys = val+value;
                const thatValue = tableArr[tempKeys];
                if (typeof thatValue === 'object') {
                  thatRead.push(tableArr[tempKeys][config.readTableKey]);
                }
              });
              readArr.push(thatRead);
            });
            resolve(readArr);
          });
        }
      }catch (e) {
        reject(e);
      }
    });
  },
  readFile: function (file, callback) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var data = e.target.result;
      var workbook = XLSX.read(data, {
        type: 'binary'
      });
      if(callback) callback(workbook);
    };
    reader.readAsBinaryString(file);
  },
  aZ:function () {
    var arr = [];
    for(var i = 65; i < 91; i++){
      arr.push(String.fromCharCode(i));
    }
    return arr;
  },
  version: '1.0.1',
  about: '本插件主要是对xlsx包的封装'
}
